from flask import request
from app.api import bp
from app.models.system_prompt import SystemPrompt
from app import db
from app.utils.errors import ValidationError, NotFoundError
from app.utils.response import APIResponse

@bp.route('/system-prompt', methods=['GET'])
def get_system_prompts():
    """获取系统提示词列表"""
    try:
        prompts = SystemPrompt.query.order_by(SystemPrompt.created_at.desc()).all()
        
        return APIResponse.success(
            data={
                'items': [prompt.to_dict() for prompt in prompts],
                'total': len(prompts)
            },
            message="System prompts retrieved successfully"
        )
    except Exception as e:
        return APIResponse.error(message=str(e))

@bp.route('/system-prompt/<int:id>', methods=['GET'])
def get_system_prompt(id):
    """获取单个系统提示词"""
    prompt = SystemPrompt.query.get_or_404(id)
    return APIResponse.success(data=prompt.to_dict())

@bp.route('/system-prompt', methods=['POST'])
def create_system_prompt():
    """创建系统提示词"""
    try:
        data = request.get_json()
        if not data:
            raise ValidationError("No input data provided")
        
        # 验证必填字段
        if not data.get('name'):
            raise ValidationError("Prompt name is required")
        if not data.get('content'):
            raise ValidationError("Prompt content is required")
        
        # 如果设置为默认，先取消其他默认提示词
        if data.get('is_default'):
            SystemPrompt.query.filter_by(is_default=True).update({'is_default': False})
        
        # 创建提示词
        prompt = SystemPrompt(
            name=data['name'],
            content=data['content'],
            description=data.get('description'),
            is_default=data.get('is_default', False)
        )
        
        db.session.add(prompt)
        db.session.commit()
        
        return APIResponse.success(
            data=prompt.to_dict(),
            message="System prompt created successfully"
        )
    except ValidationError as e:
        return APIResponse.validation_error(message=str(e))
    except Exception as e:
        db.session.rollback()
        return APIResponse.error(message=str(e)) 